<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/8 0008
 * Time: 15:18
 */

/**
 * @param $uid   用户ID
 * @param $token 用户token
 * 用户接口验证
 */
function check_token($uid,$token){
    if(!$uid || !$token) {
        json_return(204, '缺少参数uid或者token');
    }
    $true_token = \think\Db::name('member')->where(array('id'=>$uid))->value('token');

    if($token!=$true_token){
        json_return(401,'你的账号在其他地方登陆');
    }
}


// 解密user_token
function decoded_user_token($token = '')
{
    $key     = \think\Config::get('API_KEY').\think\Config::get('JWT_KEY');

    $decoded = \Firebase\JWT\JWT::decode($token, $key, array('HS256'));

    return (array) $decoded;
}

// 获取解密信息中的data
function get_member_by_token($token = '')
{
    try {
        $result = decoded_user_token($token);
    }catch (\Exception $e){
         json_return(401,'非法访问');
    }
    return $result['data'];
}


/**
 * 获取推流地址
 * 如果不传key和过期时间，将返回不含防盗链的url
 * @param bizId 您在腾讯云分配到的bizid
 *        streamId 您用来区别不同推流地址的唯一id
 *        key 安全密钥
 *        time 过期时间 sample 2016-11-12 12:00:00
 * @return String url */
function getPushUrl($bizId, $streamId, $key = null, $time = null){

    if($key && $time){
        $txTime = strtoupper(base_convert(strtotime($time),10,16));
        $livecode = $bizId."_".$streamId; //直播码
        $txSecret = md5($key.$livecode.$txTime);
        $ext_str = "?".http_build_query(array(
                "bizid"=> $bizId,
                "txSecret"=> $txSecret,
                "txTime"=> $txTime
            ));
    }
    return "rtmp://".$bizId.".livepush.myqcloud.com/live/".$livecode.(isset($ext_str) ? $ext_str : "");
}

/**
 * 获取播放地址
 * @param bizId 您在腾讯云分配到的bizid
 *        streamId 您用来区别不同推流地址的唯一id
 * @return String url */
function getPlayUrl($bizId, $streamId){
    $livecode = $bizId."_".$streamId; //直播码
    return "http://".$bizId.".liveplay.myqcloud.com/live/".$livecode.".flv";
}

/**
 * 查询直播状态
 */
function playStatus($pid = 0){
    if ($pid){
        $str = cache($pid.'playStatus');
        if (empty($str)){
            $str = '获取直播状态失败';
        }else{
            return $str;
        }
        $config = config('tencent');
        $time = strtotime("+1 day");
        $sign = md5($config['apikey'].$time);
        $url = 'http://fcgi.video.qcloud.com/common_access?appid='.$config['appid'].'&interface=Live_Channel_GetStatus&t='.$time.'&sign='.$sign.'&Param.s.channel_id='.$config['bizid'].'_'.$pid;
        $data = curl_get($url);
        $str = '';
        if ($data['ret'] == 0){
            $status = $data['output'][0]['status'];
            if ($status == 1){
                $str =  '直播中';
            }elseif ($status == 0){
                $str = '断流';
            }else{
                $str = '关闭';
            }
        }elseif ($data['ret'] == 20601){
            $str = '断流';
        }
        cache($pid.'playStatus',$str,60);
        return $str;
    }

}

/**
 * 获取直播中的房间号
 */
function online(){
    $id = cache('online');
    if (!empty($id)) return $id;
    $config = config('tencent');
    $time = strtotime("+1 day");
    $sign = md5($config['apikey'].$time);
    $url = 'http://fcgi.video.qcloud.com/common_access?appid='.$config['appid'].'&interface=Live_Channel_GetChannelList&t='.$time.'&sign='.$sign;
    $data = curl_get($url);
    $res = json_decode($data,true);
    if ($res['retcode'] == 0){
        $arr = $data['output']['channel_list'];
        $id = [];
        foreach ($arr as $v){
            if ($v['channel_status'] == 1){
                $item = explode('_',$v['channel_id']);
                $id[] = $item[1];
            }
        }
    }
    if (!empty($id)){
        cache('online',$id,30);
        return $id;
    }
}

/**
 * 获取当前直播间的观看人数
 */
function watch($pid = 0){
    if ($pid){
        $str = cache($pid.'watchNumber');
        if (!isEmpty($str)){
            return $str;
        }
        $str = 0;
        $config = config('tencent');
        $time = strtotime("+1 day");
        $sign = md5($config['apikey'].$time);
        $url = 'http://statcgi.video.qcloud.com/common_access?cmd='.$config['appid'].'&interface=Get_LiveStat&t='.$time.'&sign='.$sign.'&Param.s.stream_id='.$config['bizid'].'_'.$pid;
        $result = curl_post($url);
        $data = json_decode($result,true);
        if ($data['ret'] == 0) {
            $online = $data['output']['stream_info'][0]['online'];
            if ($online) {
                $str = $online;
            }
        }
        cache($pid.'watchNumber',$str,30);
        return $str;
    }
    return 0;
}

/**
 * 获取直播中的房间号
 */
function online1(){
    $config = config('tencent');
    $time = strtotime("+1 day");
    $sign = md5($config['apikey'].$time);
    $url = 'http://statcgi.video.qcloud.com/common_access?appid='.$config['appid'].'&interface=Get_LiveStat&Param.n.page_no=1&Param.n.page_size=20&t='.$time.'&sign='.$sign;
    $data = curl_get($url);
    dump($data);exit;
}


function execCommandLine($file){
    $result = array();

    $pathParts = pathinfo($file);        $filename = $pathParts['dirname']."/".$pathParts['filename']."_";

    $times = array(8,15,25);
    foreach ($times as $k => $v) {
        $destFilePath = $filename.$v.".jpg";
        $command = "/usr/bin/ffmpeg -i {$file} -y -f image2 -ss {$v} -vframes 1 -s 640x360 {$destFilePath}";
        exec($command);
        //chmod($filename.$v."jpg",0644);
        $destUrlPath = str_replace("/data/images/", "http://img.baidu.cn/", $destFilePath);
        $selected = $k == 0 ? "1" : "0";//默认将第一张图片作为封面图
        array_push($result,array($destUrlPath,$selected));
    }

    return $result;
}

function getCoverImages($fileUrl = 'http://pajq6n73b.bkt.clouddn.com/5734.mp4'){
    $result = array();
    if(!empty($fileUrl)){
        $filePath = str_replace("http://img.baidu.cn/", "/data/images/", $fileUrl);
        if(is_file($filePath)){
            $result = execCommandLine($filePath);
        }
    }
    return $result;
}



